package com.example.computer_exam_training_sys.service.impl;

import com.example.computer_exam_training_sys.entity.UserStudyStatistics;
import com.example.computer_exam_training_sys.entity.UserStudyStatisticsWithAnalysis;
import com.example.computer_exam_training_sys.mapper.UserAnalysisMapper;
import com.example.computer_exam_training_sys.mapper.UserLearningProgressMapper;
import com.example.computer_exam_training_sys.mapper.UserStudyStatisticsMapper;
import com.example.computer_exam_training_sys.service.UserLearningProgressService;
import com.example.computer_exam_training_sys.service.UserStudyStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;

@Service
public class UserStudyStatisticsServiceImpl implements UserStudyStatisticsService {

    @Autowired
    private UserStudyStatisticsMapper statisticsMapper;
    
    @Autowired
    private UserLearningProgressMapper learningProgressMapper;
    
    @Autowired
    private UserLearningProgressService learningProgressService;
    
    @Autowired
    private UserAnalysisMapper analysisMapper;

    @Override
    @Transactional
    public void recordStatistics(UserStudyStatistics statistics) {
        UserStudyStatistics existingStats = statisticsMapper.findByUserIdAndDate(
                statistics.getUserId(), statistics.getStatisticsDate());
        if (existingStats != null) {
            statistics.setStatisticsId(existingStats.getStatisticsId());
            statisticsMapper.update(statistics);
        } else {
            statisticsMapper.insert(statistics);
        }
        
        // 更新学习进度
        updateLearningProgress(statistics);
    }
    
    /**
     * 更新学习进度
     * 通过user_id关联user_learning_progress更新学习进度
     */
    private void updateLearningProgress(UserStudyStatistics statistics) {
        // 获取用户的所有课程ID
        List<Long> courseIds = statisticsMapper.getCourseIdsByUserId(statistics.getUserId());
        
        // 如果没有课程记录，使用默认课程ID
        if (courseIds == null || courseIds.isEmpty()) {
            courseIds = Collections.singletonList(1L); // 默认课程ID
        }
        
        // 计算完成率（基于题目正确率）
        Double completionRate = 0.0;
        if (statistics.getQuestionCount() > 0) {
            completionRate = (statistics.getCorrectCount() * 100.0) / statistics.getQuestionCount();
        }
        
        // 为每个课程更新学习进度
        for (Long courseId : courseIds) {
            try {
                learningProgressService.updateCourseLearningProgress(
                        statistics.getUserId(), 
                        courseId, 
                        completionRate, 
                        statistics.getTotalStudyTime());
            } catch (Exception e) {
                // 记录异常但不影响主流程
                System.err.println("更新课程ID " + courseId + " 的学习进度失败: " + e.getMessage());
            }
        }
    }

    @Override
    public UserStudyStatisticsWithAnalysis findByUserIdAndDateWithAnalysis(Long userId, LocalDate date) {
        return statisticsMapper.findByUserIdAndDateWithAnalysis(userId, date);
    }

    @Override
    public List<UserStudyStatisticsWithAnalysis> findByUserIdAndDateRangeWithAnalysis(
            Long userId, LocalDate startDate, LocalDate endDate) {
        return statisticsMapper.findByUserIdAndDateRangeWithAnalysis(userId, startDate, endDate);
    }

    @Override
    public Integer getTotalStudyTime(Long userId) {
        return statisticsMapper.getTotalStudyTime(userId);
    }

    @Override
    public Integer getTotalQuestionCount(Long userId) {
        return statisticsMapper.getTotalQuestionCount(userId);
    }

    @Override
    public Integer getTotalCorrectCount(Long userId) {
        return statisticsMapper.getTotalCorrectCount(userId);
    }

    @Override
    public Double getCorrectRate(Long userId) {
        Integer totalQuestions = getTotalQuestionCount(userId);
        Integer correctCount = getTotalCorrectCount(userId);
        if (totalQuestions == null || totalQuestions == 0) {
            return 0.0;
        }
        return (double) correctCount / totalQuestions;
    }

    @Override
    public Map<String, List<Object>> getStudyTimeTrend(Long userId) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(7);
        List<UserStudyStatisticsWithAnalysis> statistics = 
                statisticsMapper.findByUserIdAndDateRangeWithAnalysis(userId, startDate, endDate);
        
        Map<String, List<Object>> trend = new HashMap<>();
        List<Object> dates = new ArrayList<>();
        List<Object> times = new ArrayList<>();
        
        for (UserStudyStatisticsWithAnalysis stat : statistics) {
            dates.add(stat.getStatisticsDate());
            times.add(stat.getTotalStudyTime());
        }
        
        trend.put("dates", dates);
        trend.put("times", times);
        return trend;
    }

    @Override
    public Map<String, List<Object>> getQuestionCountTrend(Long userId) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(7);
        List<UserStudyStatisticsWithAnalysis> statistics = 
                statisticsMapper.findByUserIdAndDateRangeWithAnalysis(userId, startDate, endDate);
        
        Map<String, List<Object>> trend = new HashMap<>();
        List<Object> dates = new ArrayList<>();
        List<Object> counts = new ArrayList<>();
        
        for (UserStudyStatisticsWithAnalysis stat : statistics) {
            dates.add(stat.getStatisticsDate());
            counts.add(stat.getQuestionCount());
        }
        
        trend.put("dates", dates);
        trend.put("counts", counts);
        return trend;
    }

    @Override
    public Map<String, Object> getCorrectRateTrend(Long userId) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(7);
        List<UserStudyStatisticsWithAnalysis> statistics = 
                statisticsMapper.findByUserIdAndDateRangeWithAnalysis(userId, startDate, endDate);
        
        Map<String, Object> trend = new HashMap<>();
        List<Object> dates = new ArrayList<>();
        List<Object> rates = new ArrayList<>();
        
        for (UserStudyStatisticsWithAnalysis stat : statistics) {
            dates.add(stat.getStatisticsDate());
            double rate = stat.getQuestionCount() > 0 ? 
                    (double) stat.getCorrectCount() / stat.getQuestionCount() : 0.0;
            rates.add(rate);
        }
        
        trend.put("dates", dates);
        trend.put("rates", rates);
        return trend;
    }
    
    @Override
    @Transactional
    public void updateStatisticsFromPracticesAndExams(Long userId, LocalDate date) {
        // 创建新的统计对象
        UserStudyStatistics statistics = new UserStudyStatistics();
        statistics.setUserId(userId);
        statistics.setStatisticsDate(date);
        
        // 从user_practices获取练习数据
        Integer practiceCount = getPracticeCountByUserAndDate(userId, date);
        Integer questionCountFromPractice = getQuestionCountFromPracticeByUserAndDate(userId, date);
        Integer correctCountFromPractice = getCorrectCountFromPracticeByUserAndDate(userId, date);
        
        // 从user_exams获取考试数据
        Integer examCount = getExamCountByUserAndDate(userId, date);
        Integer questionCountFromExam = getQuestionCountFromExamByUserAndDate(userId, date);
        Integer correctCountFromExam = getCorrectCountFromExamByUserAndDate(userId, date);
        
        // 从user_learning_progress获取学习时间数据
        Integer studyTime = getStudyTimeByUserAndDate(userId, date);
        
        // 设置统计数据，处理可能的null值
        statistics.setPracticeCount(practiceCount != null ? practiceCount : 0);
        statistics.setExamCount(examCount != null ? examCount : 0);
        
        int totalQuestions = 
            (questionCountFromPractice != null ? questionCountFromPractice : 0) + 
            (questionCountFromExam != null ? questionCountFromExam : 0);
        statistics.setQuestionCount(totalQuestions);
        
        int totalCorrect = 
            (correctCountFromPractice != null ? correctCountFromPractice : 0) + 
            (correctCountFromExam != null ? correctCountFromExam : 0);
        statistics.setCorrectCount(totalCorrect);
        
        statistics.setTotalStudyTime(studyTime != null ? studyTime : 0);
        
        // 保存或更新统计数据
        recordStatistics(statistics);
    }
    
    // 从user_practices获取练习次数
    private Integer getPracticeCountByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getPracticeCountByUserAndDate(userId, date);
    }
    
    // 从user_practices获取练习题目数量
    private Integer getQuestionCountFromPracticeByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getQuestionCountFromPracticeByUserAndDate(userId, date);
    }
    
    // 从user_practices获取正确题目数量
    private Integer getCorrectCountFromPracticeByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getCorrectCountFromPracticeByUserAndDate(userId, date);
    }
    
    // 从user_exams获取考试次数
    private Integer getExamCountByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getExamCountByUserAndDate(userId, date);
    }
    
    // 从user_exams获取考试题目数量
    private Integer getQuestionCountFromExamByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getQuestionCountFromExamByUserAndDate(userId, date);
    }
    
    // 从user_exams获取正确题目数量
    private Integer getCorrectCountFromExamByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getCorrectCountFromExamByUserAndDate(userId, date);
    }
    
    // 从user_learning_progress获取学习时间
    private Integer getStudyTimeByUserAndDate(Long userId, LocalDate date) {
        return statisticsMapper.getStudyTimeByUserAndDate(userId, date);
    }
} 